package com.ruoyi.system.service.impl;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.jm.AKSeal;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SealDetailMapper;

import static com.ruoyi.common.utils.Base64Utils.ESSGetBase64Decode;
import static com.ruoyi.common.utils.Base64Utils.ESSGetBase64Encode;
import static com.ruoyi.common.utils.DateUtils.getTime;

/**
 * 印章详细Service业务层处理
 *
 * @author ess
 * @date 2021-10-25
 */
@Service
public class SealDetailServiceImpl implements ISealDetailService
{
    @Autowired
    private SealDetailMapper sealDetailMapper;

    @Autowired
    private IApplyInfoService applyInfoService;

    @Autowired
    private ISealInfoService sealInfoService;

    @Autowired
    private ICertificateService certificateService;

    @Autowired
    private IssuerUnitServiceImpl issuerUnitService;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private JmService jmService;
    /**
     * 查询印章详细
     *
     * @param sealDetailId 印章详细主键
     * @return 印章详细
     */
    @Override
    public SealDetail selectSealDetailBySealDetailId(String sealDetailId)
    {
        return composeSealDetail(sealDetailMapper.selectSealDetailBySealDetailId(sealDetailId));
    }

    /**
     * 查询印章详细列表
     *
     * @param sealDetail 印章详细
     * @return 印章详细
     */
    @Override
    public List<SealDetail> selectSealDetailList(SealDetail sealDetail)
    {
        List<SealDetail> sealDetailList = sealDetailMapper.selectSealDetailList(getESealDetail(sealDetail));
        if (sealDetailList != null && sealDetailList.size() > 0) {
            for (SealDetail a:sealDetailList) {
                composeSealDetail(a);
            }
            return sealDetailList;
        }
        return sealDetailList;
    }

    /**
     * 新增印章详细
     *
     * @param sealDetail 印章详细
     * @return 结果
     */
    @Override
    public int insertSealDetail(SealDetail sealDetail)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //根据印章详细ID获取applyInfo
        ApplyInfo applyInfo = applyInfoService.selectApplyInfoBySealDetailId(sealDetail.getSealDetailId());
        if (applyInfo==null){
            return 0;
        }
        SealInfo sealInfo = new SealInfo();
        sealInfo.setSealInfoId(IdUtils.simpleUUID());
        sealInfo.setSealName(applyInfo.getSealName());
        sealInfo.setUnitId(applyInfo.getUnitId());
        sealInfo.setSealStandard(sealDetail.getSealStandard());
        sealInfo.setInputTime(DateUtils.getTime());
        sealInfo.setInputUserId(String.valueOf(user.getUserId()));
        sealInfo.setState(0L);
        sealInfo.setJbrCardData(applyInfo.getJbrCardData());
        sealInfo.setJbrCardName(applyInfo.getJbrCardName());
        sealInfo.setJbrCardType(applyInfo.getJbrCardType());
        sealInfo.setSealDetailId(sealDetail.getSealDetailId());
        sealInfoService.insertSealInfo(sealInfo);
        //删除申请
        applyInfo.setApplyState(6L);
        applyInfoService.updateApplyInfo(applyInfo);

        sealDetail.setInputUserId(String.valueOf(user.getUserId()));
        sealDetail.setState(0L);
        //设置申请时间
        sealDetail.setInputTime(getTime());

        //如果插入的是UK印章，生产usbkeyinfo。是否UK通过印章标准判断
        if(2==sealDetail.getSealStandard()||1==sealDetail.getSealStandard()||4==sealDetail.getSealStandard()){
            try {
                String base64 = getASN1SealData(sealInfo.getSealInfoId(),sealDetail.getSealTypeId(),sealInfo.getSealName(),
                        sealDetail.getSealCertId(),sealDetail.getInputTime(),sealDetail.getSealStartTime(),sealDetail.getSealEndTime(),
                        ESSGetBase64Decode(sealDetail.getSealImg().getImgData()),sealDetail.getSealImg().getImgW()
                        ,sealDetail.getSealImg().getImgH(),sealDetail.getSealStandard());
                sealDetail.setUsbKeyInfo(base64);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return sealDetailMapper.insertSealDetail(getESealDetail(sealDetail));
    }

    /**
     * 新增印章详细
     *
     * @param sealDetail 印章详细
     * @return 结果
     */
    @Override
    public int insertSealDetail_1(SealDetail sealDetail)
    {
        return sealDetailMapper.insertSealDetail(getESealDetail(sealDetail));
    }

    /**
     * 修改印章详细
     *
     * @param sealDetail 印章详细
     * @return 结果
     */
    @Override
    public int updateSealDetail(SealDetail sealDetail)
    {
        return sealDetailMapper.updateSealDetail(getESealDetail(sealDetail));
    }

    /**
     * 批量删除印章详细
     *
     * @param sealDetailIds 需要删除的印章详细主键
     * @return 结果
     */
    @Override
    public int deleteSealDetailBySealDetailIds(String[] sealDetailIds)
    {
        return sealDetailMapper.deleteSealDetailBySealDetailIds(sealDetailIds);
    }

    /**
     * 删除印章详细信息
     *
     * @param sealDetailId 印章详细主键
     * @return 结果
     */
    @Override
    public int deleteSealDetailBySealDetailId(String sealDetailId)
    {
        return sealDetailMapper.deleteSealDetailBySealDetailId(sealDetailId);
    }


    public String getASN1SealData(String seal_id, String seal_type_id, String seal_name, String cert_id,
                                  String input_time, String seal_start_time, String seal_end_time,
                                  byte[] bPicData, int imgW, int imgH,int standard)
            throws ParseException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        int iSealType = 1;
        if ("ESS001".equals(seal_type_id)){
            iSealType = 2;
        }
        Certificate certificate = certificateService.selectCertificateByCertId(cert_id);

        byte[] bSignerCert = ESSGetBase64Decode(certificate.getCerBase64());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(input_time);
        input_time = DateUtils.parseDateToStr("yyMMddHHmmss",date);
        input_time = input_time+"Z";
        sdf = new SimpleDateFormat("yyyy-MM-dd");
        date = sdf.parse(seal_start_time);
        seal_start_time = DateUtils.parseDateToStr("yyMMddHHmmss",date);
        seal_start_time = seal_start_time+"Z";

        sdf = new SimpleDateFormat("yyyy-MM-dd");
        date = sdf.parse(seal_end_time);
        seal_end_time = DateUtils.parseDateToStr("yyMMddHHmmss",date);
        seal_end_time = seal_end_time+"Z";
        IssuerUnit issuerUnit = issuerUnitService.selectIssuerUnitSM2();
        byte[] bMakerCert =ESSGetBase64Decode(issuerUnit.getIssuerUnitRoot());
        byte[] result = null;
        if (standard==2){
//            result = GBSeal.CreateGBSeal(seal_id,2,"BJ.CLT",iSealType,seal_name,
//                    bSignerCert,input_time,seal_start_time,seal_end_time,"GIF",bPicData,imgW,imgH,
//                    bMakerCert,"1.2.156.10197.1.501",
//                    issuerUnit.getBc_pub(),
//                    issuerUnit.getBc_prv());
        }else {
            result = AKSeal.CreateAKSeal(seal_id,2,"BJ.CLT",iSealType,seal_name,
                    bSignerCert,input_time,seal_start_time,seal_end_time,"GIF",bPicData,imgW,imgH,
                    bMakerCert,"1.2.156.10197.1.501",
                    issuerUnit.getBcPub(),
                    issuerUnit.getBcPrv());
        }
        return ESSGetBase64Encode(result);
    }


    public SealDetail composeSealDetail(SealDetail sealDetail){
        if (sealDetail!=null){
//            if (!StringUtils.isEmpty(sealDetail.getSealImgId())){
//                //不为空
//                SealImg sealImg= sealImgService.selectSealImgByImgId(sealDetail.getSealImgId());
//                sealDetail.setSealImg(sealImg);
//            }
//            if (!StringUtils.isEmpty(sealDetail.getSealCertId())){
//                //不为空
//                Certificate certificate= certificateService.selectCertificateByCertId(sealDetail.getSealCertId());
//                sealDetail.setCertificate(certificate);
//            }
        }
        return getDSealDetail(sealDetail);
    }




    //加密
    private SealDetail getESealDetail(SealDetail sealDetail) {
        if (sealDetail==null){
            return null;
        }
        if (sealDetail.getSealName() != null) {
            sealDetail.setSealName(jmService.getEncryptString(sealDetail.getSealName()));
        }
        return sealDetail;
    }
    //解密
    private SealDetail getDSealDetail(SealDetail sealDetail) {
        if (sealDetail==null){
            return null;
        }
        if (sealDetail.getSealName() != null) {
            sealDetail.setSealName(jmService.getDecryptString(sealDetail.getSealName()));
        }
        if (sealDetail.getSealImg().getImgData() != null) {
            sealDetail.getSealImg().setImgData(jmService.getDecryptString(sealDetail.getSealImg().getImgData()));
        }
        return sealDetail;
    }
}
